package com.yumeng.framework.auth.shiro.filter.cus;

import com.yumeng.common.api.ApiCode;
import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.common.utils.ResponseUtils;
import com.yumeng.framework.auth.data.enums.LogoutType;
import com.yumeng.framework.auth.helper.HttpTokenHelper;
import com.yumeng.framework.auth.service.TokenService;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;

/**
 *
 * @author wxd
 * @date 2025/11/11 09:44
 */
@Slf4j
public class CustomLogoutFilter extends LogoutFilter {

    private TokenService tokenService;
    private boolean isFBS;//是否前后端分离

    public CustomLogoutFilter(TokenService tokenService, boolean isFBS){
        this.tokenService = tokenService;
        this.isFBS = isFBS;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.debug("CustomLogoutFilter::preHandle");
        BaseAuthInfo authInfo = null;
        if (tokenService != null) {
            String token = HttpTokenHelper.getToken((HttpServletRequest) request);
            if (token != null) {
                authInfo = tokenService.getAuthInfoByToken(token, false);
                tokenService.clearTokenForLogout(LogoutType.CURR_SESSION);
                log.debug("CustomLogoutFilter::tokenService::清空缓存");
            }else{
                log.warn("CustomLogoutFilter::tokenService(token缺失)");
            }
        }
        if (isFBS) {
            Subject subject = super.getSubject(request, response);
            subject.logout();//TODO 当session未生效时，该语句有意义吗？
            String msg = String.format("注销成功[%s]", authInfo != null ? authInfo.getAuthKey() : "匿名");
            log.debug("CustomLogoutFilter::subject.logout();msg:{}", msg);
            ResponseUtils.writeJson((HttpServletResponse) response, ApiCode.SUCCESS, msg);
            return false;
        }else{
            log.debug("CustomLogoutFilter::subject.logout()::redirectUrl");
            return super.preHandle(request, response);
        }

    }
}
